package v1

import (
	"fmt"
	"math"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// PageResponse 分页响应
type PageResponse struct {
	List  interface{} `json:"list" example:"[]"`     // 数据列表
	Page  int         `json:"page" example:"1"`      // 当前页码
	Size  int         `json:"size" example:"10"`     // 每页条数
	Total int64       `json:"total" example:"100"`   // 总条数
	Pages int         `json:"pages" example:"10"`    // 总页数
	First bool        `json:"first" example:"true"`  // 是否首页
	Last  bool        `json:"last" example:"false"`  // 是否尾页
	Empty bool        `json:"empty" example:"false"` // 是否空数据
}

// ListResult 列表结果
type ListResult struct {
	Items interface{} `json:"items"`
	Total int64       `json:"total"`
}

// SuccessResponse 成功响应
func SuccessResponse(c *gin.Context, msg string, data interface{}) {
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  msg,
		"data": data,
	})
}

// ErrorResponse 错误响应
func ErrorResponse(c *gin.Context, code int, msg string) {
	c.JSON(200, gin.H{
		"code": code,
		"msg":  msg,
	})
}

// GetPageInfo 获取分页信息
func GetPageInfo(c *gin.Context) (page, size int) {
	page = 1
	size = 10

	if pageStr := c.Query("page"); pageStr != "" {
		if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
			page = p
		}
	}

	if sizeStr := c.Query("size"); sizeStr != "" {
		if s, err := strconv.Atoi(sizeStr); err == nil && s > 0 {
			size = s
		}
	}

	return
}

// GetOffset 获取偏移量
func GetOffset(page, size int) int {
	return (page - 1) * size
}

// BuildPageResponse 构建分页响应
func BuildPageResponse(list interface{}, page, size int, total int64) PageResponse {
	pages := int(math.Ceil(float64(total) / float64(size)))
	return PageResponse{
		List:  list,
		Page:  page,
		Size:  size,
		Total: total,
		Pages: pages,
		First: page == 1,
		Last:  page == pages,
		Empty: total == 0,
	}
}

// GetOrderBy 获取排序条件
func GetOrderBy(c *gin.Context, defaultOrderBy string) string {
	orderBy := c.Query("order_by")
	if orderBy == "" {
		return defaultOrderBy
	}

	// 安全检查，避免SQL注入
	orderBy = strings.ReplaceAll(orderBy, "'", "")
	orderBy = strings.ReplaceAll(orderBy, "\"", "")
	orderBy = strings.ReplaceAll(orderBy, ";", "")

	if !strings.Contains(orderBy, "desc") && !strings.Contains(orderBy, "asc") {
		orderBy = fmt.Sprintf("%s desc", orderBy)
	}

	return orderBy
}

// GetSearchKeyword 获取搜索关键词
func GetSearchKeyword(c *gin.Context) string {
	return strings.TrimSpace(c.Query("keyword"))
}
